<?php

/*
 * This file is part of SoftSite.
 *
 * (c) 2012 Steve Tredinnick
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 *
 *
 * @package softsite
 * @author  Steve Tredinnick <steve.tredinnick@gmail.com>
 */

namespace Classes;

use Controllers;

class Loader
{
    private $controller;
    private $action;
    private $urlvalues;

//store the URL values on object creation
    public function __construct($urlvalues)
    {
        $this->urlvalues = $urlvalues;

        if ($this->urlvalues['controller'] == "")
        {
            $this->controller = "home";
        }
        else
        {
            $this->controller = $this->urlvalues['controller'];
        }

        if ($this->urlvalues['action'] == "")
        {
            $this->action = "index";
        }
        else
        {
            $this->action = $this->urlvalues['action'];
        }

        $this->controller .="_Controller";
    }

    //establish the requested controller as an object
    public function CreateController($debug = false)
    {
        //does the class exist?
        if (class_exists('Controllers\\'.$this->controller))
        {
            $parents = class_parents('Controllers\\'.$this->controller);

            //does the class extend the controller class?
            if (in_array("Classes\\BaseController",$parents))
            {
                //does the class contain the requested method?
                if (method_exists('Controllers\\'.$this->controller,$this->action))
                {
                    $newController = 'Controllers\\'.$this->controller;
                    return new $newController($this->action,$this->urlvalues);
                }
                else
                {
                    //bad method error
                    if($debug)
                    {
                    print "Bad Method.</BR>";
                }
                    //return new Error("badUrl",$this->urlvalues);
                }
            }
            else
            {
                //bad controller error
                if($debug)
                {
                    print "Bad Controller Doesnt extend base controller'.</BR>";
                }
                //return new Error("badUrl",$this->urlvalues);
            }
        }
        else
        {
            //bad controller error
            if($debug)
            {
                print "Bad Controller. Class ".$this->controller." does not exist</BR>";
            }
            //return new Error("badUrl",$this->urlvalues);
        }
    }
}